unit ClientMain;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdHTTPWebsocketClient, Vcl.StdCtrls, Vcl.ExtCtrls;

type
  TfrmClient = class(TForm)
    btnClient: TButton;
    lbledtPort: TLabeledEdit;
    btnClientSend: TButton;
    lbledtSendData: TLabeledEdit;
    mmo1: TMemo;
    procedure FormDestroy(Sender: TObject);
    procedure btnClientClick(Sender: TObject);
    procedure btnClientSendClick(Sender: TObject);
  private
    { Private declarations }
    FClient: TIdHTTPWebsocketClient;

    procedure OnTextData(const aText: string);
  public
    { Public declarations }
  end;

var
  frmClient: TfrmClient;

implementation

{$R *.dfm}

procedure TfrmClient.btnClientClick(Sender: TObject);
begin
  if not Assigned(FClient) then
  begin
    FClient := TIdHTTPWebsocketClient.Create(Self);
    FClient.Port := StrToIntDef(lbledtPort.Text, 9999);
    FClient.Host := 'localhost';
    FClient.OnTextData := OnTextData;
    FClient.Connect;
    FClient.UpgradeToWebsocket;
  end;
end;

procedure TfrmClient.btnClientSendClick(Sender: TObject);
begin
  if Assigned(FClient) then
  begin
    FClient.IOHandler.Write(lbledtSendData.Text);
  end;
end;

procedure TfrmClient.FormDestroy(Sender: TObject);
begin
  if Assigned(FClient) then
  begin
    FClient.Disconnect(True);
    FreeAndNil(FClient);
  end;

end;

procedure TfrmClient.OnTextData(const aText: string);
begin
  mmo1.Lines.Add(aText)
end;

end.
